package com.shixi.controller;

import com.github.pagehelper.PageInfo;
import com.shixi.domain.Product;
import com.shixi.domain.User;
import com.shixi.service.ProductService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class ProductController {

    @Autowired
    ProductService productService;

    @RequestMapping("/product")
    public String product()
    {
        return "product/product";
    }

    @ResponseBody
    @RequestMapping("/getAllProduct")
    public Map<String, Object> getAllProduct(@RequestParam("page")Integer page,
                                              @RequestParam("limit")Integer limit){
        Map<String,Object> map = new HashMap<String, Object>();
        List<Product> productList = productService.getAllProduct(page,limit);
        PageInfo<Product> pageInfo = new PageInfo<>(productList);
        map.put("code", 0);
        map.put("msg", "操作成功");
        map.put("count", pageInfo.getTotal());
        map.put("data", pageInfo.getList());
        return map;
    }

    @ResponseBody
    @RequestMapping("/search")
    public Map<String, Object> getMatchingProduct(String matchString){
        Map<String,Object> map = new HashMap<String, Object>();

        if(matchString.trim().length()==0){
            matchString = null;
        }
        List<Product> productList = productService.getMatchingProduct(matchString);
        PageInfo<Product> pageInfo = new PageInfo<>(productList);
        map.put("code", 0);
        map.put("msg", "操作成功");
        map.put("count", pageInfo.getTotal());
        map.put("data", pageInfo.getList());
        return map;
    }

    @ResponseBody
    @RequestMapping("/searchMyProduct")
    public Map<String, Object> getMatchingUserProduct(String matchString, HttpServletRequest request){
        Map<String,Object> map = new HashMap<String, Object>();
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        String username = loginUser.getUsername();
        if(matchString.trim().length()==0){
            matchString = null;
        }
        List<Product> productList = productService.getMatchingUserProduct(username, matchString);
        PageInfo<Product> pageInfo = new PageInfo<>(productList);
        map.put("code", 0);
        map.put("msg", "操作成功");
        map.put("count", pageInfo.getTotal());
        map.put("data", pageInfo.getList());
        return map;
    }

    @RequestMapping("/myproduct")
    public String tomyproduct(){
        return "product/myproduct";
    }

    @RequestMapping("/updateProductCount")
    public String updateProductCount(String id, String name, String des, String price, String count, Model model){
        model.addAttribute("id",id);
        model.addAttribute("name",name);
        model.addAttribute("des",des);
        model.addAttribute("price",price);
        model.addAttribute("count",count);
        return "product/productInfo";
    }

    @RequestMapping("/updateProductSubmit")
    @ResponseBody
    public Map<String, Object> updateProductSubmit(String id, String name, String des, String price, String count){
        Map<String, Object> map = new HashMap<>();
        System.out.println(id+name+des+count);
        boolean updateresult = productService.updateProductInfo(Integer.parseInt(id),name,des,Integer.parseInt(price),Integer.parseInt(count));
        if(updateresult==true){
            map.put("code", 0);
        }else {
            map.put("code", -1);
        }
        return map;
    }

    @RequestMapping("/getUserProduct")
    @ResponseBody
    public Map<String, Object> getUserProduct(@RequestParam("page")Integer page,
                                              @RequestParam("limit")Integer limit,
                                              HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        String username = loginUser.getUsername();

        List<Product> productList = productService.getUserProduct(page, limit, username);
        PageInfo<Product> pageInfo = new PageInfo<>(productList);
        map.put("code", 0);
        map.put("msg", "操作成功");
        map.put("count", pageInfo.getTotal());
        map.put("data", pageInfo.getList());
        return map;
    }

    @RequestMapping("/deleteProduct")
    @ResponseBody
    public Map<String, Object> deleteProduct(String id){
        Map<String, Object> map = new HashMap<>();

        boolean result = productService.deleteProductById(Integer.parseInt(id));
        if(result==true){
            map.put("code", 0);
        }else {
            map.put("code", -1);
        }
        return map;
    }

    @RequestMapping("/addProduct")
    public String addProduct(){
        return "product/addProduct";
    }


    @RequestMapping("/addProductSubmit")
    public String addProductSubmit(Model model, String goods_name, String goods_count, String goods_price, String goods_des,MultipartFile file, HttpServletRequest request)
    {
        Map<String, Object> map = new HashMap<>();
        if(file!=null)
        {
            //先指定上传路径，获取对应物理路径
            String targetDirectory =  "E:/productImages";
            String temFileName = file.getOriginalFilename();
            int dot = temFileName.lastIndexOf('.');
            String ext = "";  //文件后缀名
            if ((dot > -1) && (dot < (temFileName.length() - 1))) {
                ext = temFileName.substring(dot + 1);
            }
            // 其他文件格式不处理
            if ("png".equalsIgnoreCase(ext) || "jpg".equalsIgnoreCase(ext) || "gif".equalsIgnoreCase(ext)) {
                // 重命名上传的文件名
                String targetFileName = renameFileName(temFileName);
                // 保存的新文件
                File target = new File(targetDirectory, targetFileName);
                System.out.println(target.getAbsolutePath());
                try {
                    // 保存文件
                    FileUtils.copyInputStreamToFile(file.getInputStream(), target);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                User loginUser = (User) request.getSession().getAttribute("loginUser");
                String picurl = "/productImages/" + targetFileName;
                boolean result = productService.insertProduct(loginUser.getUsername(), goods_name, goods_des, goods_count, goods_price, picurl);
                if(result==true){
                    model.addAttribute("msg","添加成功");
                    return "product/addProduct";
                }else{
                    model.addAttribute("msg","添加失败");
                    return "product/addProduct";
                }
            }
            model.addAttribute("msg","选择的文件不是图片，请重新选择！");
            return "product/addProduct";
        }
        model.addAttribute("msg","未选择文件！");
        return "product/addProduct";
    }

    /*文件重命名方法*/
    public static String renameFileName(String fileName) {
        String formatDate = new SimpleDateFormat("yyMMddHHmmss").format(new Date()); // 当前时间字符串
        String extension = fileName.substring(fileName.lastIndexOf(".")); // 文件后缀

        return  formatDate + extension;
    }

}
